#!/bin/bash

# Railway 部署脚本
# Railway 支持 SQLite 和文件系统

echo "🚀 准备 Railway 部署..."

# 1. 创建 Railway 配置文件
cat > railway.json << EOF
{
  "deploy": {
    "startCommand": "npm run start",
    "restartPolicyType": "always",
    "healthcheckPath": "/api/auth/verify",
    "healthcheckTimeout": 30000
  }
}
EOF

# 2. 更新 package.json 添加 Railway 脚本
npm pkg set scripts.railway="npm run build && npm run start"

# 3. 创建 Railway 环境变量设置脚本
cat > set-railway-env.sh << 'EOF'
#!/bin/bash
# 在 Railway 控制台中设置这些环境变量

echo "📝 需要在 Railway 控制台设置以下环境变量："
echo ""
echo "NODE_ENV=production"
echo "PORT=3001"
echo "DATABASE_PATH=/app/data/delivery-management.db"
echo "BACKUP_ENABLED=true"
echo ""
echo "🔧 部署命令："
echo "npm install -g @railway/cli"
echo "railway login"
echo "railway init"
echo "railway up"
EOF

chmod +x set-railway-env.sh

# 4. 创建 Render 部署配置
cat > render.yaml << EOF
services:
  - type: web
    name: delivery-record-frontend
    env: node
    buildCommand: npm install && npm run build
    startCommand: npm run start
    healthCheckPath: /api/auth/verify
    envVars:
      - key: NODE_ENV
        value: production
      - key: PORT
        value: 3001
      - key: DATABASE_PATH
        value: /opt/render/project/src/data/delivery-management.db
    disk:
      name: delivery-data
      mountPath: /opt/render/project/src/data
      sizeGB: 10
EOF

# 5. 创建 Fly.io 配置
cat > fly.toml << EOF
app = "delivery-record-frontend"
primary_region = "hkg"

[http_service]
  internal_port = 3001
  force_https = true
  auto_stop_machines = true
  auto_start_machines = true
  min_machines_running = 1
  processes = ["app"]

[env]
  NODE_ENV = "production"
  PORT = "3001"
  DATABASE_PATH = "/data/delivery-management.db"

[[mounts]]
  source = "delivery_data"
  destination = "/data"

[[services]]
  protocol = "tcp"
  internal_port = 3001
  processes = ["app"]

  [[services.ports]]
    port = 80
    handlers = ["http"]
    force_https = true

  [[services.ports]]
    port = 443
    handlers = ["tls", "http"]

[build]
  builder = "heroku/nodejs"

[deploy]
  release_command = "npm run build"
  strategy = "rolling"
EOF

# 6. 创建 Heroku 部署脚本
cat > heroku-deploy.sh << 'EOF'
#!/bin/bash

echo "🚀 准备 Heroku 部署..."

# 注意：Heroku 不支持 SQLite，需要使用 PostgreSQL
echo "⚠️  警告：Heroku 不支持 SQLite，需要修改为 PostgreSQL"
echo ""
echo "📝 需要的步骤："
echo "1. 安装 Heroku CLI"
echo "2. 创建 Heroku 应用: heroku create your-app-name"
echo "3. 添加 PostgreSQL: heroku addons:create heroku-postgresql:hobby-dev"
echo "4. 修改代码以支持 PostgreSQL"
echo "5. 部署: git push heroku main"
EOF

chmod +x heroku-deploy.sh

echo "✅ 云平台部署配置已创建："
echo "   - Railway: railway.json + set-railway-env.sh"
echo "   - Render: render.yaml"
echo "   - Fly.io: fly.toml"
echo "   - Heroku: heroku-deploy.sh"
echo ""
echo "🔧 推荐部署平台："
echo "   1. Railway (支持 SQLite) - 最佳选择"
echo "   2. Render (支持持久化存储)"
echo "   3. Fly.io (支持 volumes)"
echo "   4. Heroku (需要改用 PostgreSQL)"